package com.example.learn;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.widget.ContentLoadingProgressBar;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {

    private AppCompatImageView backImageView = null;
    private AppCompatImageView goImageView = null;
    private AppCompatImageView refreshImageView = null;
    private AppCompatImageView favImageView = null;
    private AppCompatImageView sendImageView = null;
    private AppCompatEditText linkEditText = null;
    private SwipeRefreshLayout mainSwipeRefreshLayout = null;
    private WebView mainWebView = null;
    private ContentLoadingProgressBar mainProgressBar = null;

    public static SharedPreferences sharedPreferences = null;
    public static SharedPreferences.Editor editor = null;
    public static ArrayList<TagsData> tagsArrayList = new ArrayList<>();

    @SuppressLint({"SetJavaScriptEnabled", "CommitPrefEdits"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        backImageView = findViewById(R.id.backImageView);
        goImageView = findViewById(R.id.goImageView);
        refreshImageView = findViewById(R.id.refreshImageView);
        favImageView = findViewById(R.id.favImageView);
        sendImageView = findViewById(R.id.sendImageView);
        linkEditText = findViewById(R.id.linkEditText);
        mainSwipeRefreshLayout = findViewById(R.id.mainSwipeRefreshLayout);
        mainWebView = findViewById(R.id.mainWebView);
        mainProgressBar = findViewById(R.id.mainProgressBar);

        sharedPreferences = getSharedPreferences("Test", MODE_PRIVATE);
        editor = sharedPreferences.edit();

        //将本地存储的json换成arrayList;
        String tags = sharedPreferences.getString("tags", "");
        if (!tags.isEmpty()) {
            try {
                tagsArrayList.clear();
                TagsData data;
                JSONObject jsonObject = new JSONObject();
                JSONArray jsonArray = new JSONArray(tags);
                for (int i = 0; i < jsonArray.length(); i++) {
                    jsonObject = jsonArray.getJSONObject(i);
                    data = new TagsData();
                    data.setTitle(jsonObject.getString("title"));
                    data.setUrl(jsonObject.getString("url"));
                    tagsArrayList.add(data);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        mainSwipeRefreshLayout.setColorSchemeColors(
                getResources().getColor(R.color.colorAccent),
                getResources().getColor(R.color.colorPrimaryDark),
                getResources().getColor(R.color.colorPrimary)
        );

        WebSettings webSettings = mainWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mainWebView.loadUrl(Objects.requireNonNull(linkEditText.getText()).toString());

        mainWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                linkEditText.setText(url);
                mainWebView.loadUrl(url);
                return true;
            }
        });

        mainWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                mainProgressBar.setVisibility(View.VISIBLE);
                mainProgressBar.setProgress(newProgress);
                if (newProgress == 100) {
                    mainProgressBar.setVisibility(View.GONE);
                }
            }
        });

        backImageView.setOnClickListener(v -> {
            mainWebView.goBack();//后退
        });

        goImageView.setOnClickListener(v -> {
            mainWebView.goForward();//前进
        });

        refreshImageView.setOnClickListener(v -> {
            mainWebView.reload();//重新加载
        });

        favImageView.setOnClickListener(v -> {
            TagsData data;
            for (int i = 0; i < tagsArrayList.size(); i++) {
                data = tagsArrayList.get(i);
                if (data.getTitle().equals(mainWebView.getTitle()) || data.getUrl().equals(mainWebView.getUrl())) {
                    Toast.makeText(MainActivity.this, "此书签已存在~", Toast.LENGTH_LONG).show();
                    return;
                }
            }
            data = new TagsData();
            data.setTitle(mainWebView.getTitle());
            data.setUrl(mainWebView.getUrl());
            tagsArrayList.add(data);
            Toast.makeText(MainActivity.this, "已加入书签~", Toast.LENGTH_LONG).show();
            //保存数据到本地储存,把arraylist转换为json数据,写入
            editor.putString("tags", new Gson().toJson(tagsArrayList));
            //一定要写,否则数据不存入
            editor.apply();
        });

        favImageView.setOnLongClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, TagsActivity.class);
            intent.putExtra("test", "这是从MainActivity传过来的数据~");
            startActivityForResult(intent, 999);
            return false;
        });

        sendImageView.setOnClickListener(v -> {
            //mainWebView.loadUrl(Objects.requireNonNull(linkEditText.getText()).toString());
            startActivity(new Intent(this, MainActivity.class));
        });

        mainSwipeRefreshLayout.setOnRefreshListener(() ->
                new Handler().postDelayed(() -> {
                    mainSwipeRefreshLayout.setRefreshing(false);
                    mainWebView.reload();
                }, 3000)
        );

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //判断页面是不是正常返回
        if (resultCode == RESULT_OK) {
            //判断是不是自己做的标识
            if (requestCode == 999) {
                assert data != null;
                String url = data.getStringExtra("url");
                //Toast.makeText(MainActivity.this, url, Toast.LENGTH_SHORT).show();
                mainWebView.loadUrl(url);
            }
        }
    }

}
